/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld.demo;

import com.sun.spot.core.resources.transducers.ISwitch;
import com.sun.spot.core.resources.transducers.ISwitchListener;
import com.sun.spot.core.resources.transducers.ITriColorLED;
import com.sun.spot.core.resources.transducers.LEDColor;
import com.sun.spot.core.resources.transducers.SwitchEvent;
import com.sun.spot.core.util.Utils;
import com.sun.spot.edemo.EDemoBoard;
import com.sun.spot.multihop.io.j2me.radiogram.Radiogram;
import com.sun.spot.multihop.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;
import javax.microedition.io.Connector;

/**
 *
 * @author me
 */
public class RadioSwitchReporter implements ISwitchListener {
    private RadiogramConnection xConn = null;
    private Radiogram xrg;
    private ISwitch[] sw = EDemoBoard.getInstance().getSwitches();
    private ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
    private LEDColor[] colors = new LEDColor[leds.length];

    public RadioSwitchReporter() {
        try {
            xConn = (RadiogramConnection)Connector.open("radiogram://broadcast:46");
            xConn.setMaxBroadcastHops(0);
            xrg = (Radiogram)xConn.newDatagram(xConn.getMaximumLength());
            sw[0].addISwitchListener(this);
            System.out.println("Switch Reporter Initialized");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void close() {
        if (xConn != null) {
            try {
                xConn.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            xConn = null;
        }
    }

    public void switchPressed(SwitchEvent arg0) {
        System.out.println("Switch pressed!");
        if (xConn != null) {
            try {
                for (int i=0; i<leds.length; i++) {
                    colors[i] = leds[i].getColor();
                    leds[i].setColor(LEDColor.WHITE);
                    leds[i].setOn();
                }
                Utils.sleep(50);
                for (int i=0; i<leds.length; i++) {
                    leds[i].setOff();
                    leds[i].setColor(colors[i]);
                }
                xrg.reset();
                xrg.writeBoolean(true);
                xConn.send(xrg);
            } catch (IOException iOException) {
            }
        }
    }

    public void switchReleased(SwitchEvent arg0) {
    }

}
